package com.smile.cloud.gateway.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.smile.cloud.common.base.constant.CommonConstant;
import com.smile.cloud.gateway.constant.FilterOrderConstant;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class TraceLogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        // token 校验 优先级最高
        return FilterOrderConstant.ONE_LEVEL;
    }

    /**
     * 过滤器拦截
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = exchange.getRequest().getHeaders().getFirst(CommonConstant.TRACE_ID_HEADER);
        if (!StrUtil.isNotBlank(traceId)) {
            traceId = IdUtil.fastSimpleUUID();
        }
        //日志id放入本地
        MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
        //日志id放入请求头
        String finalTraceId = traceId;
        ServerHttpRequest request = exchange.getRequest().mutate().headers(h -> h.add(CommonConstant.TRACE_ID_HEADER, finalTraceId)).build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        return chain.filter(build);
    }

}